<?php

namespace addons\qingdong\model;

use addons\qingdong\library\Ku;
use app\common\model\Area;
use think\Db;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;
/**
 *客户
 */
class Customer Extends Model {
	use SoftDelete;
    // 表名,不含前缀
    protected $name = 'qingdong_customer';
	// 开启自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	// 定义时间戳字段名
	protected $createTime = 'createtime';
	protected $updateTime = 'updatetime';
	protected $deleteTime = 'deletetime';


	//获取创建时间
	public function getCreatetimeAttr($value) {
		return date('Y-m-d H:i:s', $value);
	}


	//创建人
	public function createStaff() {
		return $this->hasOne(Staff::class, 'id', 'create_staff_id')->field('id,name,post');
	}


	//负责人
	public function ownerStaff() {
		return $this->hasOne(Staff::class, 'id', 'owner_staff_id')->field('id,name,img');
	}


	//获取联系人
	public function contacts() {
		return $this->hasOne(Contacts::class, 'customer_id', 'id')->order('is_major desc')->field('id,customer_id,name,mobile,email');
	}
    //获取联系人
    public function contact() {
        return $this->belongsTo(Contacts::class,'id','customer_id',  [], 'LEFT')->field('id,customer_id,name,mobile,email')->setEagerlyType(0);;
	}

    //获取客户相关信息
    public function customerOther() {
        return $this->belongsTo(CustomerOther::class,'id','id');
	}

	public static function withtrash(){
	    return self::withTrashed();
    }

	public static function getList() {
	    $staff = Staff::info();
        $staff_id = $staff->id;
        $whereStaff = function ($query) use ($staff_id) {
            $query->where(['ro_staff_id' => ['like', "%,{$staff_id},%"]])
                ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%")
                ->whereOr(['owner_staff_id' => ['in', Staff::getMyStaffIds()]]);
        };
		return self::where($whereStaff)->field('id,name')->select();
	}


	//创建客户
	public static function createCustomer($params,$leads_id=null,$reminds_id=null) {
		//自定义字段
		$other = [];
		foreach ($params as $name => $val) {
			if (strstr($name,'other_') !== false) {
                if(is_array($val)){
                    $other[$name] = implode(',',$val);
                }else{
                    $other[$name] = $val;
                }
				unset($params[$name]);
			}else{
                if($params[$name] === ''){
                    $params[$name]=NULL;
                }
            }
		}
		$staff = Staff::info();
		if(empty($staff)){
            // 验证失败 输出错误信息
            throw new Exception('账号不存在');
		}
        $params['create_staff_id'] = $staff->id;
        $params['owner_staff_id']  = $staff->id;
		$params['next_time']   = date('Y-m-d H:i:s');
		$params['last_time']   = date('Y-m-d H:i:s');
		$params['receivetime'] = time();
		$customer              = new self;

        $result = $customer->allowField(true)->save($params);
		$lastId=$customer->getLastInsID();
		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($customer->getError());
		}
		$otherModel = new CustomerOther();
		if ($otherModel->save(['id' => $lastId, 'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)]) === false) {
			// 验证失败 输出错误信息
			throw new Exception($otherModel->getError());
		}
        if(isset($leads_id) && $leads_id){
            Leads::where(['id' => $leads_id])->update(['is_transform' => 1, 'customer_id' => $lastId]);
        }
        if (isset($reminds_id['reminds_id']) && $reminds_id['reminds_id']) {//发送通知
            $staff_ids = explode(',', $reminds_id['reminds_id']);
            foreach ($staff_ids as $staff_id) {
                //发送通知
                Message::addMessage(Message::CUSTOMER_TYPE, $lastId, $staff_id, $staff->id);
            }
        }

        OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $lastId, '创建客户');
		//新增跟进记录
		Record::quickCreateRecord(Record::CUSTOMER_TYPE, $lastId, '新增客户：' . $params['name']);
		return $lastId;
	}


	/**
	 *修改客户信息
	 */
	public static function updateCustomer($params) {
		//自定义字段
		$other = [];
		foreach ($params as $name => $val) {
			if (strstr($name,'other_') !== false) {
                if(is_array($val)){
                    $other[$name] = implode(',',$val);
                }else{
                    $other[$name] = $val;
                }
				unset($params[$name]);
			}else{
                if($params[$name] === ''){
                    $params[$name]=NULL;
                }
            }
		}

		$customer = new self;
		// 调用当前模型对应的User验证器类进行数据验证
		$result = $customer->save($params, ['id' => $params['id']]);
		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($customer->getError());
		}
		$otherModel = new CustomerOther();
		$otherFind = $otherModel->where(['id' => $params['id']])->find();
		if($otherFind){
            $resInfo = $otherModel->save(['otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)],['id' => $params['id']]);
        }else{
            $resInfo = $otherModel->save(['id' => $params['id'],'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)]);
        }
		if ( $resInfo === false) {
			// 验证失败 输出错误信息
			throw new Exception($otherModel->getError());
		}
        //同步数据
        $ku = new Ku();
        $ku->editCustomer($params);
		return true;
	}

    /**
     * 导入客户
     * @param $data
     * @return bool
     */
	public static function importCustomer($data) {
		$addCustomers = [];
		$addOther     = [];
        $addcontacts = [];
		$addLog=[];
		foreach ($data as $params) {
			//自定义字段
			$other = [];
			foreach ($params as $name => $val) {
				if (strstr($name, 'other_') !== false) {
                    if(is_array($val)){
                        $other[$name] = implode(',',$val);
                    }else{
                        $other[$name] = $val;
                    }
					unset($params[$name]);
				}else{
                    if($params[$name] === ''){
                        $params[$name]=NULL;
                    }
                }
			}
			$other['id']           = $params['id'];
			$params['next_time']   = date('Y-m-d H:i:s');
			$params['receivetime'] = time();
			$params['createtime'] = time();
			$addOther[]            = ['id' => $params['id'], 'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)];
            $addcontacts[] = ['customer_id' => $params['id'],'is_major'=>1,'name'=>$params['name'],'mobile'=>$params['mobile'],'createtime'=>time(),'updatetime'=>time()];

			$addLog[] = [
				'content'        => '导入客户',
				'operation_type' => 2,
				'operation_id'   => 30,
				'relation_type'  => OperationLog::CUSTOMER_TYPE,
				'relation_id'    => $params['id'],
				'createtime'     => time()
			];
			$addCustomers[]        = $params;
		}

		$customer = new self;
		// 调用当前模型对应的User验证器类进行数据验证
		$result = $customer->allowField(true)->insertAll($addCustomers);

		$otherModel = new CustomerOther();
		$otherModel->allowField(true)->insertAll($addOther);

        //联系人
        $contactsModel = new Contacts();
        $contactsModel->allowField(true)->insertAll($addcontacts);

		$logModel = new OperationLog();
		$logModel->allowField(true)->insertAll($addLog);

		return true;
	}

	/**
	 *移入公海
	 */
	public static function moveSeas($id) {
        $row = Customer::where(['id' => $id])->find();
        $row = $row->toArray();
        $row = CustomerOther::getOther($row);
        $seastype=Seastype::where([])->select();
        $seasIds=[];
        foreach ($seastype as $r){
            $rules=json_decode($r['rules'],true)?:[];
            $is_rule=0;//权限是否匹配
            foreach ($rules as $n=>$e){

                if($n == 'area_ids'){//区域
                    $area=Area::where(['id'=>['in',$e]])->column('name');
                    foreach ($area as $a){
                        $rs=preg_match("/^{$a}/i",$row['address'],$res);
                        if($rs){
                            $is_rule=1;
                        }
                    }
                }else if (isset($row[$n]) && $row[$n]) {
                    if (is_string($e)) {
                        $e = explode(',', $e);
                    }
                    $rn = explode(',', $row[$n]);
                    $intersect = array_intersect($e, $rn);
                    if($intersect){
                        $is_rule=1;
                    }
                }

            }
            if ($is_rule == 1) {
                $seasIds[] = $r['id'];
            }

        }
        if(empty($seasIds)){
            $seasIds[]=1;//默认公海
        }
        $seas_id = ',' . implode(',', $seasIds) . ',';
        if (Customer::where(['id' => $id])->update(['owner_staff_id' => 0,
                'seas_id' => $seas_id,'sea_time'=>time()]) == false) {
            throw new Exception('修改失败');
        }
		OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $id, '将客户放入公海');

		return true;
	}


	/**
	 * 转移客户
	 */
	public static function transfer($id, $staff_id) {
		Db::startTrans();
		try {
			if (Customer::where(['id' => $id])->update([
					'owner_staff_id' => $staff_id,
					'updatetime'     => time()
				]) == false) {
				throw new Exception('修改失败');
			}
			if (Contacts::where(['customer_id' => $id])->count()) {//存在联系人 则修改负责人
				if (Contacts::where(['customer_id' => $id])->update([
						'owner_staff_id' => $staff_id,
						'updatetime'     => time()
					]) == false) {
					throw new Exception('修改失败');
				}
			}
			$staff = Staff::get($staff_id);
			OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $id, '将客户转移给：' . $staff['name']);

			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			throw new Exception($e->getMessage());
		}

		return true;
	}


	/**
	 * 批量转移客户
	 */
	public static function batchTransfer($ids, $staff_id) {
		Db::startTrans();
		try {
			if (Customer::where(['id' => ['in',$ids]])->update([
					'owner_staff_id' => $staff_id,
					'updatetime'     => time()
				]) == false) {
				throw new Exception('修改失败');
			}
			if (Contacts::where(['customer_id' => ['in',$ids]])->count()) {//存在联系人 则修改负责人
				if (Contacts::where(['customer_id' => ['in',$ids]])->update([
						'owner_staff_id' => $staff_id,
						'updatetime'     => time()
					]) == false) {
					throw new Exception('修改失败');
				}
			}
			$staff = Staff::get($staff_id);
			foreach ($ids as $id){
				OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $id, '将客户转移给：' . $staff['name']);
			}

			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			throw new Exception($e->getMessage());
		}

		return true;
	}


	/**
	 * 领取客户
	 */
	public static function receive($customer_id) {
		$staff    = Staff::info();
		$where=['owner_staff_id' => 0];
		if($customer_id){
			$where['id']=$customer_id;
		}
		$customer = Customer::where($where)->find();
		Db::startTrans();
		try {
			$id       = $customer['id'];
			$staff_id = $staff->id;
			if (Customer::where(['id' => $customer['id']])->update(['owner_staff_id' => $staff->id,'receivetime'=>time()]) == false) {
				throw new Exception('修改失败');
			}
			if (Contacts::where(['customer_id' => $id])->count()) {//存在联系人 则修改负责人
				if (Contacts::where(['customer_id' => $id])->update([
						'owner_staff_id' => $staff_id,
						'updatetime'     => time()
					]) == false) {
					throw new Exception('修改失败');
				}
			}

			OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $customer['id'], '领取了客户');

			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			throw new Exception($e->getMessage());
		}

		return $customer['id'];
	}
}
